import LoadModel from '@/three/utils/LoadModel';
import React, { useEffect } from 'react';
import * as THREE from 'three';
import { CanvasTexture } from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import Styles from './index.module.scss';
import { SkinViewer } from 'skinview3d';

function PThree() {
  const renderElement = React.createRef<HTMLDivElement>();
  useEffect(() => {
    const scene = new THREE.Scene();

    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

    const sv = new SkinViewer({
      canvas: document.createElement('canvas'),
      width: 100,
      height: 100,
      skin: new URL('../../../assets/three/skin/test.png', import.meta.url).href,
    });
    let player = sv.playerObject;
    player.scale.set(0.05, 0.05, 0.05);
    player.position.set(0, 0, 0);

    console.log(player);

    // @ts-expect-error
    scene.add(player);

    (async () => {
      const [KRM] = await LoadModel(
        new URL('../../../assets/three/KRM-963-53/KRM-963-53.mtl', import.meta.url).href,
        new URL('../../../assets/three/KRM-963-53/KRM-963-53.obj', import.meta.url).href,
      );
      const [ps] = await LoadModel(
        new URL('../../../assets/three/PointsStore/PointsStore.mtl', import.meta.url).href,
        new URL('../../../assets/three/PointsStore/PointsStore.obj', import.meta.url).href,
      );
      const [logo] = await LoadModel(
        new URL('../../../assets/three/PdcLogo/PdcLogoModel.mtl', import.meta.url).href,
        new URL('../../../assets/three/PdcLogo/PdcLogoModel.obj', import.meta.url).href,
      );
      const [momoPhone, phoneMTL] = await LoadModel(
        new URL('../../../assets/three/momoPhone/momo_phone_binding.mtl', import.meta.url).href,
        new URL('../../../assets/three/momoPhone/momo_phone_binding.obj', import.meta.url).href,
      );

      const animePhoneElement = document.createElement('canvas'),
        phone_img = document.createElement('img'),
        ctx = animePhoneElement.getContext('2d')!;
      // ctx
      phone_img.src = new URL('../../../assets/three/momoPhone/momophone_screen.png', import.meta.url).href;
      phone_img.addEventListener('load', () => {
        animePhoneElement.width = phone_img.width;
        animePhoneElement.height = phone_img.height;
        ctx.drawImage(phone_img, 0, 0);
        let imageData = ctx.getImageData(0, 0, phone_img.width, phone_img.height);
        const ONE_FPS_WH = phone_img.width,
          imgArray: ImageData[] = [];
        for (let i = 0; i < imageData.height / imageData.width; i++) {
          imgArray.push(ctx.getImageData(0, i * ONE_FPS_WH, ONE_FPS_WH, ONE_FPS_WH));
        }

        // console.log(imgArray);

        let index = 0;
        ctx.clearRect(0, 0, imageData.width, imageData.height);
        animePhoneElement.width = ONE_FPS_WH;
        animePhoneElement.height = ONE_FPS_WH;
        // phoneMTL.materials['m_28ad134f-7280-fcc3-b70b-dff4530beeb4'].map = new CanvasTexture(animePhoneElement);
        const NewMeshPhongM = new THREE.MeshPhongMaterial({
          map: new CanvasTexture(
            animePhoneElement,
            undefined,
            undefined,
            undefined,
            THREE.NearestFilter,
            THREE.NearestFilter,
          ),
        });
        // @ts-expect-error
        phoneMTL.materials['m_28ad134f-7280-fcc3-b70b-dff4530beeb4'].map = NewMeshPhongM.map;

        console.log(phoneMTL.materials['m_28ad134f-7280-fcc3-b70b-dff4530beeb4']);

        // @ts-expect-error
        window.PREVIEW_NAMESPACE = {
          showMomo() {
            // @ts-expect-error
            phoneMTL.materials['m_28ad134f-7280-fcc3-b70b-dff4530beeb4'].color = new THREE.Color(223, 26, 168);
          },
          hideMomo() {
            // @ts-expect-error
            phoneMTL.materials['m_28ad134f-7280-fcc3-b70b-dff4530beeb4'].color = new THREE.Color(0, 0, 0);
          },
        };
        setInterval(() => {
          ctx.putImageData(imgArray[index], 0, 0);
          index++;
          if (index >= imgArray.length) index = 0;
          NewMeshPhongM.map!.needsUpdate = true;

          // phoneMTL.materials['m_28ad134f-7280-fcc3-b70b-dff4530beeb4'].needsUpdate = true;
          // NewMeshPhongM.map!
        }, 1000 / 30);
      });
      // new URL('../../../assets/three/momoPhone/momophone_screen.png', import.meta.url).href
      // ctx?.fillRect(0, 0, 128, 7926);

      logo.scale.set(0.4, 0.4, 0.4);
      ps.add(logo);
      ps.position.setX(-5);
      KRM.position.setX(5);
      scene.add(ps, KRM);
      momoPhone.scale.set(8, 8, 8);
      momoPhone.position.set(-0.5, -9, 3);
      momoPhone.rotateY(Math.PI);
      momoPhone.rotateX(-Math.PI * 0.44);
      const rightArm = player.children[0].getObjectByName('rightArm')!;
      // @ts-expect-error
      rightArm.add(momoPhone);
      rightArm.rotateX(-Math.PI * 0.2);
      // @ts-expect-error
      window._THREE_PLAYER_ = player;
      console.log('rightArm', player.children[0].getObjectByName('rightArm'));
    })();

    const light = new THREE.AmbientLight(0xffffff);
    scene.add(light);
    camera.position.z = 5;

    const renderer = new THREE.WebGLRenderer({ alpha: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderElement.current?.appendChild(renderer.domElement);

    const controls = new OrbitControls(camera, renderer.domElement);
    // controls.enablePan = false;
    // controls.enableZoom = false;

    function animate() {
      requestAnimationFrame(animate);
      renderer.render(scene, camera);
    }
    animate();
  }, []);
  // document.body.appendChild( renderer.domElement );
  return <div className={`${Styles.p_three} w100 h100`} ref={renderElement}></div>;
}

export default PThree;
